package com.tim.app.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.ActivityManager;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.SmoothSwitchScreenUtil;
import com.application.library.util.TimeUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.manager.WindowUtils;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Story;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.NetworkHost;
import com.tim.app.server.result.RedbagListBean;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.SignInBean;
import com.tim.app.service.MusicService;
import com.tim.app.ui.dialog.SignInDialog;
import com.tim.app.ui.fragment.home.HomeDynamicFragment;
import com.tim.app.ui.fragment.home.HomeFoundFragment;
import com.tim.app.ui.fragment.home.HomeMeFragment;
import com.tim.app.ui.fragment.home.HomePageFragment;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";

    private FragmentTabHost mTabHost;
    private long last_back_time = 0;
    private Class mFragmentArray[] = {HomeFoundFragment.class,
            HomePageFragment.class, HomeDynamicFragment.class, HomeMeFragment.class};
    private String[] tabTitles;
    private int[] tabIcons = {R.drawable.tab_selected_selector, R.drawable.tab_question_and_answer_selector, R.drawable.tab_dynamic_selector, R.drawable.tab_me_selector};
    private ImageView iv_sign_in;
    private static int toFragmentIndex = -1;

    private boolean isInFirstPage = true;//是否处于一级界面
    private static int currentFragmentIndex;

    public static final int TAB_INDEX_FOUND = 0;//发现的TAB
    public static final int TAB_INDEX_SELECTED = 1;//精选的TAB
    public static final int TAB_INDEX_DYNAMIC = 2;//动态的TAB
    public static final int TAB_INDEX_ME = 3;//我的TAB

    ObjectAnimator animator;

    public ImageView ivPlay;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        context.startActivity(intent);
    }


    public static void start(Context context, int fragmentIndex) {
        toFragmentIndex = fragmentIndex;
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        SmoothSwitchScreenUtil.smoothSwitchScreen(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        iv_sign_in = (ImageView) findViewById(R.id.iv_sign_in);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        tabTitles = getResources().getStringArray(R.array.tab_titles);

        ivPlay = (ImageView) findViewById(R.id.ivPlay);
        iv_sign_in.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        EventManager.ins().registListener(EventTag.ON_READ_MESSAGE_COUNT, eventListener);
        EventManager.ins().registListener(EventTag.ON_OFFICIAL_UNREAD_MESSAGE_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.GET_GOTO_CURRENT_PLAY_DETAIL, eventListener);
        EventManager.ins().registListener(EventTag.GET_PLAY_STATED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_STOP, eventListener);

        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if (tabId.equals(tabTitles[0])) {
                    currentFragmentIndex = TAB_INDEX_FOUND;
                } else if (tabId.equals(tabTitles[1])) {
                    currentFragmentIndex = TAB_INDEX_SELECTED;
                } else if (tabId.equals(tabTitles[2])) {
                    currentFragmentIndex = TAB_INDEX_DYNAMIC;
                } else if (tabId.equals(tabTitles[3])) {
//
                }
            }
        });
        registerObservers(true);
        animator = ObjectAnimator.ofFloat(ivPlay, "rotation", 0f, 359.0f);
        LinearInterpolator lin = new LinearInterpolator();
        animator.setDuration(2000);
        animator.setInterpolator(lin);
        animator.setRepeatCount(-1);//设置动画重复次数
        animator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式
    }

    @Override
    public void initData() {
        int count = mFragmentArray.length;
        for (int i = 0; i < count; i++) {
            // 给每个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(tabTitles[i])
                    .setIndicator(getTabView(i));
            // 将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, mFragmentArray[i], null);
        }
        mTabHost.getTabWidget().setDividerDrawable(R.color.transparent);
        mTabHost.getTabWidget().getChildTabViewAt(3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserManager.ins().isLogin()) {
                    currentFragmentIndex = TAB_INDEX_ME;
                    mTabHost.setCurrentTab(currentFragmentIndex);
                } else {
                    ViewGT.gotoLoginActivity(MainActivity.this);
                }
            }
        });

        mTabHost.getTabWidget().getChildTabViewAt(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentFragmentIndex == TAB_INDEX_FOUND) {
                    EventManager.ins().sendEvent(EventTag.DO_REFRESH_FOUND, 0, 0, null);
                } else {
                    mTabHost.setCurrentTab(0);
                    mTabHost.getTabWidget().requestFocus(View.FOCUS_FORWARD);
                }
            }
        });
        mTabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentFragmentIndex == TAB_INDEX_SELECTED) {
                    EventManager.ins().sendEvent(EventTag.DO_REFRESH_SELECTED, 0, 0, null);
                } else {
                    mTabHost.setCurrentTab(1);
                    mTabHost.getTabWidget().requestFocus(View.FOCUS_FORWARD);
                }
            }
        });
        mTabHost.getTabWidget().getChildTabViewAt(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentFragmentIndex == TAB_INDEX_DYNAMIC) {
                    EventManager.ins().sendEvent(EventTag.DO_REFRESH_DYNAMIC, 0, 0, null);
                } else {
                    mTabHost.setCurrentTab(2);
                    mTabHost.getTabWidget().requestFocus(View.FOCUS_FORWARD);
                }
            }
        });
        if (getIntent().hasExtra("isGogoToLogin")) {
            if (getIntent().getBooleanExtra("isGogoToLogin", false)) {
                ViewGT.gotoLoginActivityCanBack(this);
            }
        }
        showMesageView();
        String value = UserManager.ins().getValue(UserManager.LAST_SIGN_TIME);
        if (!TextUtils.isEmpty(value)) {
            boolean sameDayOfMillis;
            if (RT.HOST == NetworkHost.DEBUG) {
                sameDayOfMillis = TimeUtil.isSameDayOfMillis(Long.parseLong(value), System.currentTimeMillis() + 100000000);
            } else {
                sameDayOfMillis = TimeUtil.isSameDayOfMillis(Long.parseLong(value), System.currentTimeMillis());
            }
            if (!sameDayOfMillis) {
                getSignInfo();
            }
        } else {
            getSignInfo();
        }

        if (UserManager.ins().isLogin()) {
            getRedbagList();
        } else {
            List<RedbagListBean.ResBean.ArraylistBean> list = new ArrayList();
            RedbagListBean.ResBean.ArraylistBean redBagBean = new RedbagListBean.ResBean.ArraylistBean();
            redBagBean.setId(1);
            redBagBean.setMoney(1);
            list.add(redBagBean);
            WindowUtils.getInStance().setRedbagList(list);
            WindowUtils.getInStance().setContext(this);
            WindowUtils.getInStance().showPopupWindow();
        }
    }

    private RedbagListBean redbagListBean;

    private void getRedbagList() {
        API_User.ins().getRedbagList(TAG, UserManager.ins().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                //    Log.e("tag", "resultValue====" + resultValue);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    redbagListBean = new Gson().fromJson(resultValue, RedbagListBean.class);
                    if (redbagListBean.getRes().getArraylist().size() != 0) {
                        WindowUtils inStance = WindowUtils.getInStance();
                        inStance.setRedbagList(redbagListBean.getRes().getArraylist());
                        inStance.setContext(MainActivity.this);
                        inStance.showPopupWindow();
                    }
                }
                return false;
            }
        });
    }

    private void getSignInfo() {
        API_User.ins().getSignInfo(TAG, UserManager.ins().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                //     Log.e("tag", "resultValue====" + resultValue);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    SignInBean result = new Gson().fromJson(resultValue, SignInBean.class);
                    //        UserManager.ins().saveLastSign(result.getRes().getHashmap().getUser().getSignTime() + "");
                    iv_sign_in.setVisibility(View.VISIBLE);
                    hashmap = result.getRes().getHashmap();
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("hashmap", hashmap);
                    signInDialog = new SignInDialog();
                    signInDialog.setOnDimissListener(new SignInDialog.OnDimissListener() {
                        @Override
                        public void onDismiss() {
                            iv_sign_in.setVisibility(View.GONE);
                        }

                    });
                    signInDialog.setArguments(bundle);
                }
                return false;
            }
        });
    }

    SignInBean.ResBean.HashmapBean hashmap;

    private void setMessageView(boolean isShow) {
//        View view = mTabHost.getTabWidget().getChildTabViewAt(2).findViewById(R.id.ivUnreadMessageFlag);
//        if (isShow) {
//            view.setVisibility(View.VISIBLE);
//        } else {
//            view.setVisibility(View.GONE);
//        }
        EventManager.ins().sendEvent(EventTag.ON_MESSAGE_STATED_CHANGED, 0, 0, isShow);
    }

    public boolean isInFirstPage() {
        return isInFirstPage;
    }

    public void setInFirstPage(boolean inFirstPage) {
        isInFirstPage = inFirstPage;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //   WindowUtils.showPopupWindow(MainActivity.this);
        WindowUtils.getInStance().showPopupWindow();
        SmoothSwitchScreenUtil.smoothSwitchScreen(this);
        if (toFragmentIndex != -1) {
            mTabHost.setCurrentTab(toFragmentIndex);
            toFragmentIndex = -1;
        }
        EventManager.ins().sendEvent(EventTag.ON_GET_PLAY_STATED, 0, 0, null);
//        if (redbagListBean != null && redbagListBean.getRes().getArraylist().size() != 0) {
//            WindowUtils inStance = WindowUtils.getInStance();
//            inStance.setRedbagList(redbagListBean.getRes().getArraylist());
//            inStance.setContext(MainActivity.this);
//            inStance.showPopupWindow();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        WindowUtils.getInStance().hidePopupWindow();
    }

    private SignInDialog signInDialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPlay:
                EventManager.ins().sendEvent(EventTag.ON_GOTO_CURRENT_PLAY, 0, 0, null);
                break;
            case R.id.iv_sign_in:
//                if(signInDialog==null){
//                    signInDialog = new SignInDialog();
//                }
                //   Bundle bundle = new Bundle();
                //   bundle.putParcelable("hashmap", hashmap);
                //    signInDialog = new SignInDialog();
                //   signInDialog.setArguments(bundle);
                signInDialog.show(getSupportFragmentManager(), "");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_OFFICIAL_UNREAD_MESSAGE_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_READ_MESSAGE_COUNT, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        EventManager.ins().removeListener(EventTag.GET_GOTO_CURRENT_PLAY_DETAIL, eventListener);
        EventManager.ins().removeListener(EventTag.GET_PLAY_STATED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_STOP, eventListener);
        registerObservers(false);
        super.onDestroy();
    }

    /**
     * ********************** 收消息，处理状态变化 ************************
     */
    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(incomingMessageObserver, register);
    }


    Observer<List<IMMessage>> incomingMessageObserver =
            new Observer<List<IMMessage>>() {
                @Override
                public void onEvent(List<IMMessage> messages) {
                    try {
                        requestMessages();
                        final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                        EventManager.ins().sendEvent(EventTag.ON_READ_MESSAGE_COUNT, 0, 0, unReadMessageTotalCount);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

    private void requestMessages() {
        // 查询最近联系人列表数据
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {

            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable exception) {
                if (code != ResponseCode.RES_SUCCESS || recents == null) {
                    return;
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (!isInFirstPage() && currentFragmentIndex == TAB_INDEX_SELECTED) {
            EventManager.ins().sendEvent(EventTag.GO_BACK, 0, 0, currentFragmentIndex);
            return;
        }
        long current_time = System.currentTimeMillis();
        if (current_time - last_back_time > 2000) {
            ToastUtil.showToast(getString(R.string.app_exit));
            last_back_time = current_time;
        } else {
            MobclickAgent.onKillProcess(this);
            ActivityManager.ins().AppExit(this);
            Intent intent = new Intent(this, MusicService.class);
            stopService(intent);
        }
    }

    /**
     * 消息的view
     */
    private void showMesageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                    final int unReadNoticeCount = DaoFactory.getNoticeDao().getUnReadMessageCount();
                    if (unReadMessageTotalCount > 0 || unReadNoticeCount > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                EventManager.ins().sendEvent(EventTag.ON_READ_MESSAGE_COUNT, 0, 0, unReadMessageTotalCount);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ACCOUNT_LOGIN:
                    getSignInfo();
                    getRedbagList();
                    break;
                case EventTag.ACCOUNT_LOGOUT:
                    setMessageView(false);
                    break;
                case EventTag.ON_OFFICIAL_UNREAD_MESSAGE_CHANGED:
                    showMesageView();
                    break;
                case EventTag.ON_READ_MESSAGE_COUNT:
                    int count = (int) dataobj;
                    if (count > 0 || DaoFactory.getNoticeDao().getUnReadMessageCount() > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                        setMessageView(true);
                    } else {
                        setMessageView(false);
                    }
                    break;
                case EventTag.GET_GOTO_CURRENT_PLAY_DETAIL:
                    int index = arg1;
                    ArrayList<Story> storyList = (ArrayList<Story>) dataobj;
                    StoryDetailActivity.start(MainActivity.this, storyList, index, false);
                    break;
                case EventTag.GET_PLAY_STATED:
                    boolean isplay = (Boolean) dataobj;
                    if (isplay) {
                        ivPlay.setVisibility(View.VISIBLE);
                        animator.start();
                    } else {
                        animator.cancel();
                        ivPlay.setVisibility(View.GONE);
                    }
                    break;
                case EventTag.ON_PLAY:
                    ivPlay.setVisibility(View.VISIBLE);
                    animator.start();
                    break;
                case EventTag.ON_PAUSE:
                case EventTag.ON_STOP:
                    animator.cancel();
                    ivPlay.setVisibility(View.GONE);
                    break;
            }
        }
    };


    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item_view, null);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        ImageView iv_tab_icon = (ImageView) view.findViewById(R.id.iv_tab_icon);
        tv_title.setText(tabTitles[position]);
        iv_tab_icon.setImageResource(tabIcons[position]);
        return view;
    }

    private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>(
            10);

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyOnTouchListener listener : onTouchListeners) {
            listener.onTouch(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.add(myOnTouchListener);
    }

    public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
        onTouchListeners.remove(myOnTouchListener);
    }

    public static interface MyOnTouchListener {
        public boolean onTouch(MotionEvent ev);
    }

}
